package com.xfatm.simplebrowser;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.xfatm.simplebrowser.entity.BrowserSetting;
import com.xfatm.simplebrowser.ui.ActivityUtil;
import com.xfatm.simplebrowser.ui.BaseActivity;
import com.xfatm.simplebrowser.ui.BottomDialog;
import com.xfatm.simplebrowser.ui.MainWebView;
import com.xfatm.simplebrowser.util.ActivityManageUtils;
import com.xfatm.simplebrowser.util.BeanManageUtils;
import com.xfatm.simplebrowser.util.SharedPreferencesUtils;

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityUtil.initUI(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化配置文件
        if(BrowserSetting.getSetting()==null){
            new BrowserSetting(this);
        }
        viewInit();
    }

    //回退
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        MainWebView mainWebView=BeanManageUtils.getBean("mainWebView",MainWebView.class);
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(mainWebView!=null&&mainWebView.canGoBack()){
                mainWebView.goBack();
            }else{
                Long lastDownTime=BeanManageUtils.getBean("lastDownTime",Long.class);
                if(lastDownTime==null||System.currentTimeMillis()-lastDownTime>500){
                    Toast.makeText(BeanManageUtils.getBean(BeanManageUtils.SHOW_ACTIVITY, Activity.class),"再按一次退出",Toast.LENGTH_SHORT).show();
                    BeanManageUtils.saveBean("lastDownTime",System.currentTimeMillis());
                }else if(lastDownTime!=null&&System.currentTimeMillis()-lastDownTime<=500){
                    ActivityManageUtils.finishAll();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    /**
     * 控件初始化
     */
    private void viewInit(){

        //初始化输入地址的EditText
        EditText editText=findViewById(R.id.urlText);
        BeanManageUtils.saveBean(R.id.urlText,editText);
        editText.setSingleLine(true);
        //初始化go按钮
        Button goButton=findViewById(R.id.goButton);
        BeanManageUtils.saveBean("goButton",goButton);
        //设置go按钮的初始状态为go     refresh     close
        BeanManageUtils.saveBean("goButtonStatus","go");
        //初始化加载进度条
        ProgressBar progressBar=findViewById(R.id.loadProgressBar);
        BeanManageUtils.saveBean("loadProgressBar",progressBar);
        //初始化webview
        final MainWebView mainWebView=findViewById(R.id.mainWebView);
        mainWebView.loadUrl("file:///android_asset/index.html");
        BeanManageUtils.saveBean("mainWebView",mainWebView);
        BeanManageUtils.saveBean(BeanManageUtils.SHOW_ACTIVITY,this);

        //底部导航菜单
        LinearLayout bottomNavMenu=findViewById(R.id.bottomNavMenu);
        BeanManageUtils.saveBean(R.id.bottomNavMenu,bottomNavMenu);

        //初始化输入法
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        BeanManageUtils.saveBean("input",mInputMethodManager);

        LinearLayout linearLayout=findViewById(R.id.headLayout);
        BeanManageUtils.saveBean("headLayout",linearLayout);

        RelativeLayout bodyLayout=findViewById(R.id.bodyLayout);
        BeanManageUtils.saveBean("bodyLayout",bodyLayout);

        //输入框焦点时间初始化
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                //谁知goButton状态
                Button goButton=BeanManageUtils.getBean("goButton",Button.class);
                EditText et=(EditText)view;
                if (b) {
                    // 此处为得到焦点时的处理内容
                    String url=BeanManageUtils.getBean("mainWebView",MainWebView.class).getUrl();
                    if(url.startsWith("file")){
                        url="";
                    }
                    et.setText(url);
                    et.selectAll();
                    goButton.setText(R.string.rightIcon);
                    BeanManageUtils.saveBean("goButtonStatus","go");

                    //隐藏菜单
                    LinearLayout navMenu=BeanManageUtils.getBean(R.id.bottomNavMenu,LinearLayout.class);
                    navMenu.setVisibility(View.GONE);
                } else {
                    // 此处为失去焦点时的处理内容
                    //隐藏输入法
                    InputMethodManager mInputMethodManager=BeanManageUtils.getBean("input",InputMethodManager.class);
                    if (mInputMethodManager.isActive()) {
                        mInputMethodManager.hideSoftInputFromWindow(et.getWindowToken(), 0);// 隐藏输入法
                    }
                    //显示菜单
                    LinearLayout navMenu=BeanManageUtils.getBean(R.id.bottomNavMenu,LinearLayout.class);
                    navMenu.setVisibility(View.VISIBLE);
                }
            }
        });

        //webView获取焦点
        mainWebView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    Button goButton=BeanManageUtils.getBean("goButton",Button.class);
                    EditText et=BeanManageUtils.getBean(R.id.urlText,EditText.class);
                    et.setText(BeanManageUtils.getBean("mainWebView",MainWebView.class).getTitle());
                    goButton.setText(R.string.refreshIcon);
                    BeanManageUtils.saveBean("goButtonStatus","refresh");
                }
            }
        });

        //GO按钮初始化
        goButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                EditText urlText=BeanManageUtils.getBean(R.id.urlText,EditText.class);
                MainWebView mainWebView1=BeanManageUtils.getBean("mainWebView",MainWebView.class);
                Button goButton=BeanManageUtils.getBean("goButton",Button.class);

                //当前按钮状态 刷新，取消，前进
                if("go".equals(BeanManageUtils.getString("goButtonStatus"))){
                    //隐藏输入法
                    InputMethodManager mInputMethodManager=BeanManageUtils.getBean("input",InputMethodManager.class);
                    if (mInputMethodManager.isActive()) {
                        mInputMethodManager.hideSoftInputFromWindow(urlText.getWindowToken(), 0);// 隐藏输入法
                    }

                    String url=urlText.getText().toString();
                    if(url.trim().equals("")){
                        urlText.setText(mainWebView.getUrl());
                        return;
                    }
                    if(!url.startsWith("http")){
                        url="http://"+url;
                        urlText.setText(url);
                    }
                    mainWebView.loadUrl(url);
                    goButton.setText(R.string.closeIcon);
                    BeanManageUtils.saveBean("goButtonStatus","close");
                }else if("refresh".equals(BeanManageUtils.getString("goButtonStatus"))){
                    mainWebView.reload();
                    goButton.setText(R.string.closeIcon);
                    BeanManageUtils.saveBean("goButtonStatus","close");
                }else if("close".equals(BeanManageUtils.getString("goButtonStatus"))){
                    mainWebView.stopLoading();
                    goButton.setText(R.string.refreshIcon);
                    BeanManageUtils.saveBean("goButtonStatus","refresh");
                }

                view.setFocusable(true);
                view.setFocusableInTouchMode(true);
                view.requestFocus();
                view.requestFocusFromTouch();
            }
        });

        //回退按钮初始化
        Button lastUrl=findViewById(R.id.lastUrl);
        BeanManageUtils.saveBean("lastUrl",lastUrl);
        lastUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainWebView mainWebView1=BeanManageUtils.getBean("mainWebView",MainWebView.class);
                if(mainWebView.canGoBack()){
                    mainWebView.goBack();
                }
            }
        });

        //前进按钮初始化
        Button nextUrl=findViewById(R.id.nextUrl);
        BeanManageUtils.saveBean("nextUrl",nextUrl);
        nextUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainWebView mainWebView1=BeanManageUtils.getBean("mainWebView",MainWebView.class);
                if(mainWebView.canGoForward()){
                    mainWebView.goForward();
                }
            }
        });

        //主页按钮初始化
        Button home=findViewById(R.id.home);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainWebView mainWebView1=BeanManageUtils.getBean("mainWebView",MainWebView.class);
                mainWebView1.loadUrl("file:///android_asset/index.html");
            }
        });

        //菜单按钮
        Button menu=findViewById(R.id.menu);
        menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomDialog bottomDialog=new BottomDialog(v.getContext());
                bottomDialog.show();
            }
        });

    }

}
